/**
 * Created by Administrator on 2018/3/28.
 */
//这个控件和图形表一起使用
;
(function($) {

    var default_option = {
        runtimes: 'html5,flash,silverlight,html4',
        multi_selection: false, //是否可以多选
        container: 'container', //选择文件和开始上传按钮所在的容器
        info_content: 'ossfile', //上传进度条等信息显示容器ID
        select_button: 'selectfiles', //选择文件按钮ID
        post_botton: 'postfiles', //开始上传按钮ID
        flash_swf_url: window.location.origin + '/js/oss/lib/plupload-2.1.2/js/Moxie.swf',
        silverlight_xap_url: window.location.origin + '/js/oss/lib/plupload-2.1.2/js/Moxie.xap',
        oss_url: 'http://oss.aliyuncs.com', //oss头地址
        max_file_size: '10mb', //最大只能上传10mb的文件
        prevent_duplicates: false, //不允许选取重复文件
        mime_types: [ //只允许上传图片和zip,rar文件
            {
                title: "Image files",
                extensions: "jpg,gif,png,bmp,jpeg"
            },
            {
                title: "Zip files",
                extensions: "zip,rar"
            }
        ],
        sign_url : 'upload/image_sign', //获取签名地址
        sign_param : {},
        access_token: '', //这是我自己使用的
        beforeUpload: function(up, file){},
        uploading: function(up, file){},
        done: function(up, file, info){},
    };

    //私有参数
    var accessid = '';
    var accesskey = '';
    var host = '';
    var policyBase64 = '';
    var signature = '';
    var callbackbody = '';
    var filename = '';
    var key = '';
    var expire = 0;
    var g_object_name = '';
    var g_object_name_type = '';
    var now = timestamp = Date.parse(new Date()) / 1000;
    var uploader;

    layui.$.initUploader = function(option) {
        default_option = layui.$.extend(true, default_option, option);
        //初始化上传控件
        uploader = getUpload();
        uploader.init();
        return uploader;
    }

    layui.$.autoUpload = function() {
        set_upload_param(uploader, '', false);
    }

    layui.$.getOption = function() {
        return default_option;
    }

    function send_request() {
        var xmlhttp = null;
        if(window.XMLHttpRequest) {
            xmlhttp = new XMLHttpRequest();
        } else if(window.ActiveXObject) {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }

        if(xmlhttp != null) {
            serverUrl = default_option.sign_url
            if(serverUrl.indexOf('?') < 0){
                serverUrl += '?';
            }
            for(var sign_parm_key in default_option.sign_param){
                serverUrl += '&'+sign_parm_key+'='+default_option.sign_param[sign_parm_key];
            }
            xmlhttp.open("POST", serverUrl, false);
            xmlhttp.send(null);
            return xmlhttp.responseText
        } else {
            alert("Your browser does not support XMLHTTP.");
        }
    }

    function check_object_radio() {
        var tt = document.getElementsByName('myradio');
        for(var i = 0; i < tt.length; i++) {
            if(tt[i].checked) {
                g_object_name_type = tt[i].value;
                break;
            }
        }
    }

    function get_signature() {
        //可以判断当前expire是否超过了当前时间,如果超过了当前时间,就重新取一下.3s 做为缓冲
        now = timestamp = Date.parse(new Date()) / 1000;
        if(expire < now + 3) {
            body = send_request();
            var obj = eval("(" + body + ")");
            host = obj['oss']['host'];
            policyBase64 = obj['oss']['policy'];
            accessid = obj['oss']['accessid'];
            signature = obj['oss']['signature'];
            expire = parseInt(obj['oss']['expire']);
            callbackbody = obj['oss']['callback'];
            key = obj['oss']['dir'];
            return true;
        }
        return false;
    };

    function random_string(len) {
        len = len || 32;
        var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
        var maxPos = chars.length;
        var pwd = '';
        for(i = 0; i < len; i++) {
            pwd += chars.charAt(Math.floor(Math.random() * maxPos));
        }
        return pwd;
    }

    function get_suffix(filename) {
        pos = filename.lastIndexOf('.')
        suffix = ''
        if(pos != -1) {
            suffix = filename.substring(pos)
        }
        return suffix;
    }

    function calculate_object_name(filename) {
        suffix = get_suffix(filename)
        g_object_name = key + random_string(15) + suffix
        return ''
    }

    function set_upload_param(up, filename, ret) {
        if(ret == false) {
            ret = get_signature()
        }
        g_object_name = key;
        if(filename != '') {
            suffix = get_suffix(filename)
            calculate_object_name(filename)
        }
        new_multipart_params = {
            'key': g_object_name,
            'policy': policyBase64,
            'OSSAccessKeyId': accessid,
            'success_action_status': '200', //让服务端返回200,不然，默认会返回204
            'callback': callbackbody,
            'signature': signature,
        };

        /**
         * 
         * 
         * 
         * 
         * 
         * 
         * 这里可以自己加参数到oss回调里面
         * 
         * 
         * 
         * 
         * 
         * 
         */
        new_multipart_params['x:aaa'] = 'aaa';
        new_multipart_params['x:bbb'] = 'bbb';
        /**
         * 
         * 
         * 
         * 
         * 
         * 
         * 这里可以自己加参数到oss回调里面
         * 
         * 
         * 
         * 
         * 
         * 
         */

        up.setOption({
            'url': host,
            'multipart_params': new_multipart_params
        });

        up.start();
    }

    function getUpload() {
        var uploader = new plupload.Uploader({
            runtimes: default_option.runtimes,
            browse_button: default_option.select_button,
            multi_selection: default_option.multi_selection,
            container: document.getElementById(default_option.container),
            flash_swf_url: default_option.flash_swf_url,
            silverlight_xap_url: default_option.silverlight_xap_url,
            url: default_option.oss_url,

            filters: {
                mime_types: default_option.mime_types,
                max_file_size: default_option.max_file_size,
                prevent_duplicates: default_option.prevent_duplicates
            },

            init: {
                PostInit: function() {

                },

                FilesAdded: function(up, files) {
                    set_upload_param(uploader, '', false);
                },

                BeforeUpload: function(up, file) {
                    typeof default_option.beforeUpload === 'function' && default_option.beforeUpload(up, file);
                    set_upload_param(up, file.name, true);
                },

                UploadProgress: function(up, file) {
                    typeof default_option.uploading === 'function' && default_option.uploading(up, file);
                },

                FileUploaded: function(up, file, info) {
                    if(info.status == 200) {
                        typeof default_option.done === 'function' && default_option.done(up, file, info);
                    } else {

                    }
                },

                Error: function(up, err) {
                    if(err.code == -600) {
                        console.log('选择的文件太大了');
                    } else if(err.code == -601) {
                        console.log('选择的文件后缀不对');
                    } else if(err.code == -602) {
                        console.log('这个文件已经上传过一遍了');
                    } else {
                        console.log(err.response);
                    }
                }
            }
        });
        return uploader;
    }

})(layui.jQuery);